//
//  String+InputRules.swift
//  NetWork
//
//  Created by Delin Meng 孟德林 on 2018/9/21.
//  Copyright © 2018年 Delin Meng 孟德林. All rights reserved.
//

import UIKit


// MARK: - 更加精确的转换货币 比string更精确

extension NSDecimalNumber{
    /// 转换货币格式
    /// - authors: xiaochao.su
    /// - date: 2017年11月08日
    ///
    /// Usage:
    ///
    ///    140000.formatAsCurrency(currencyCode: "CNY")
    ///
    /// - parameters:
    ///   - currencyCode: 货币字符串 例如 CNY,USD,EUR,GBP
    ///   - digits: 保留几位小数
    /// - returns: ¥144,000
    func formatAsCurrency(currencyCode: String = "CNY",digits:Int16 = 2) -> String {

        let behavior = NSDecimalNumberHandler(roundingMode: .plain, scale: digits, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
        let newValue = self.rounding(accordingToBehavior: behavior)
        print(newValue.doubleValue)

        let currencyFormatter = NumberFormatter()
        currencyFormatter.locale = Locale(identifier: "zh-CN")
        currencyFormatter.numberStyle = .currency
        currencyFormatter.currencyCode = currencyCode
        currencyFormatter.maximumFractionDigits = Int(digits)

        if digits > 0 {
            if ((Int(newValue.doubleValue * (pow(10, Double(digits)))) % 10) == 0) {
                currencyFormatter.maximumFractionDigits = 1
            }

            if ((Int(newValue.doubleValue * (pow(10, Double(digits)))) % 100) == 0){
                currencyFormatter.maximumFractionDigits = 0
            }
        }


        if let str = currencyFormatter.string(from: newValue){
            return str
        }else{
            return "\(self)"
        }
    }
}


/// MARK: 字符串转数字处理
extension String {

    /// 转换成指定货币格式（默认￥）
    ///
    /// - Parameters:
    ///   - currencyCode: 货币字符串 例如 CNY,USD,EUR,GBP
    ///   - digits: 保留几位小数
    ///   - placeHolder:
    /// - Returns: ￥152,572
    func formatAsCurrency(currencyCode: String = "CNY",digits:Int = 2,placeHolder:String = "- -") -> String {

        if let d = Double(self){
            let currencyFormatter = NumberFormatter()
            currencyFormatter.locale = Locale(identifier: "zh-CN")
            currencyFormatter.numberStyle = .currency
            currencyFormatter.currencyCode = currencyCode
            currencyFormatter.maximumFractionDigits = digits


            //小数点后为零不显示小数
            if digits > 0 {
                if ((Int(d * (pow(10, Double(digits)))) % 10) == 0){
                    currencyFormatter.maximumFractionDigits = 1
                }

                if ((Int(d * (pow(10, Double(digits)))) % 100) == 0){
                    currencyFormatter.maximumFractionDigits = 0
                }
            }

            if let str = currencyFormatter.string(from: NSNumber(value: d)){
                return str
            }else{
                return "\(self)"
            }
        }else{
            return placeHolder
        }
    }
}


/// MARK: 输入规则相关
extension String {

    /// 四位一个空格
    ///
    /// - Parameter str:
    /// - Returns:
    private func convertAccountString() -> String {
        var numberArr = [String]()
        let a = (self.count % 4 == 0) ? (self.count / 4) : (self.count / 4 + 1)
        for i in 0..<a {
            let begin = i * 4
            let end = (( i * 4 + 4) > self.count) ? self.count : (i * 4 + 4)
            if let rang = Range.init(NSMakeRange(begin, end - begin)) {
                let substr = self.substring(with: rang)
                numberArr.append(substr)
            }
        }
        return numberArr.joined(separator:" ")
    }


    ///Find Assign Characters
    func index(from: Int) -> Index {
        return self.index(startIndex, offsetBy: from)
    }

    func substring(from: Int) -> String {
        let fromIndex = index(from: from)
        return substring(from: fromIndex)
    }

    func substring(to: Int) -> String {
        let toIndex = index(from: to)
        return substring(to: toIndex)
    }

    func substring(with r: Range<Int>) -> String {
        let startIndex = index(from: r.lowerBound)
        let endIndex = index(from: r.upperBound)
        return substring(with: startIndex..<endIndex)
    }


}



// MARK: - 通过字符串计算高度、宽度、Rect
extension String {

    public func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

        return ceil(boundingBox.height)
    }

    public func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

        return ceil(boundingBox.width)
    }


    public func rectOfFontString(fontSize: CGFloat, fontName: String = "PingFangSC-Regular") -> CGRect? {

        var font = UIFont.init(name: fontName, size: fontSize)
        if font == nil {
            font = UIFont.systemFont(ofSize: fontSize)
        }
        guard let _ = font else {
            return nil
        }
        let text = NSString.init(string: self)
        let attributes = [NSAttributedStringKey.font : font!]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let rect = text.boundingRect(with: CGSize.init(width: 400, height: 999), options: option, attributes: attributes, context: nil)
        return rect
    }


}
